#!/usr/bin/env python
# -*- coding:utf-8 -*-

from controller.wordController import WordController

import datetime
import math

from flask import current_app ,make_response ,jsonify,g
from sqlalchemy import or_,select
from werkzeug.security import generate_password_hash, check_password_hash

from app import db
from models.wordbook import Wordbook
from models.plan import Plan
from models.word_dictionary import WordDictionary
from models.user_word_times import UserWordTimes
from models.word_wordbook_append import WordWordbookAppend
from models.word import Word
from models.user import User
from utils import commons
from utils.generate_id import GenerateID
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN
from utils.rsa_encryption_decryption import RSAEncryptionDecryption

class WordService(WordController):

    def get_words_by_plan(self, plan, learned_words):
        # 定义子查询
        subquery = db.session.query(WordDictionary.word_id).filter_by(
            dictionary_id=plan.dictionary_id,
            is_delete=0
        ).subquery()

        words = db.session.query(Word).filter(
            Word.word_id.in_(select(subquery.c.word_id)),  # 显式地传递 select 构造对象
            Word.word_id.notin_(learned_words)
        ).all()

        if plan.plan_type == 0:  # 顺序学习（按字母顺序）
            words.sort(key=lambda x: x.word_name)
        elif plan.plan_type == 1:  # 逆序学习（按字母逆序）
            words.sort(key=lambda x: x.word_name, reverse=True)
        elif plan.plan_type == 2:  # 随机学习
            import random
            random.shuffle(words)

        return words

    def get_next_word(self, user_id,plan_id):
        plan = db.session.query(Plan).filter_by(plan_id=plan_id,user_id=user_id, is_delete=0).first()
        if not plan:
            return None, "No plan found for this user", None

        learned_words = self.get_user_learned_words(user_id) #返回一个列表
        words = self.get_words_by_plan(plan, learned_words)

        if not words:
            return None, "No words available for this plan", plan

        next_word = words[0]
        return next_word, "Next word retrieved successfully", plan

    # 获取用户已学单词
    def get_user_learned_words(self, user_id):
        learned_words = db.session.query(UserWordTimes.word_id).filter_by(user_id=user_id, is_delete=0).all()
        return [word_id for word_id, in learned_words]

    # 更新用户已学单词
    def update_learned_word(self, user_id, word_id):
        learned_word = db.session.query(UserWordTimes).filter_by(user_id=user_id, word_id=word_id).first()
        if learned_word:
            learned_word.learn_times += 1
        else:
            learned_word = UserWordTimes(user_word_id=GenerateID.create_random_id() , user_id=user_id, word_id=word_id,is_get=0, learn_times=1,is_delete=0)

        db.session.add(learned_word)
        db.session.commit()

    # 获取用户计划信息
    def get_user_plan_info(self, user_id):
        plan = db.session.query(Plan).filter_by(user_id=user_id, is_delete=0).first()
        if not plan:
            return None, "No plan found for this user"
        return plan

    # 获取用户剩余目标
    def get_remaining_target(self, user_id, plan):
        if plan.plan_quantity:
            learned_count = len(self.get_user_learned_words(user_id))

            remaining_count = plan.plan_quantity - learned_count % plan.plan_quantity
            return remaining_count, "words"
        elif plan.plan_time:
            # 假设你有一个方法来计算剩余时间
            # remaining_time = self.calculate_remaining_time(user_id, plan)
            # return remaining_time, "minutes"
            return plan.plan_time, "minutes"
        return 0, "unknown"

    @classmethod
    def is_get(cls, user_id, word_id):
        print(user_id, word_id)
        learned_word = db.session.query(UserWordTimes).filter_by(user_id=user_id, word_id=word_id).first()
        if not learned_word:
            return {'code': RET.NODATA, 'message': 'Word not found for this user', 'data': None}
        print(learned_word)
        learned_word.is_get = 1
        db.session.commit()

        return {'code': RET.OK, 'message': 'Word marked as mastered successfully', 'data': {'word_id': word_id}}
        db.session.close()